#include "jsondatamanager.h"
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QImage>

JsonDataManager::JsonDataManager(QObject *parent) : QObject(parent)
{

}

void JsonDataManager::addSpotData(int time, int pos, int mode, int endTime){
    spotData data;
    data.time=time;
    data.end_time=endTime;
    data.pos=pos;
    data.mode=mode;
    this->spotdata.append(data);
}
void JsonDataManager::clearSpotData(){
    this->spotdata.clear();
}
void JsonDataManager::setRhythmData(QString name, int duration, int rhythmNum){
    this->songdata.name=name;
    this->songdata.duration=duration;
    this->songdata.rhythmNum=rhythmNum;
}
void JsonDataManager::comressDataToJson(){
    QJsonObject song;
    song.insert("name",this->songdata.name);
    song.insert("duration",this->songdata.duration);
    song.insert("rhythmNum",this->songdata.rhythmNum);


    QJsonArray spotArray;
    QList<QJsonObject> spotList;
    for(int a=0;a<this->spotdata.count();a++){
        QJsonObject spotroot;
        QJsonObject spot;
        spot.insert("time",this->spotdata.at(a).time);
        spot.insert("pos",this->spotdata.at(a).pos);
        spot.insert("mode",this->spotdata.at(a).mode);
        spot.insert("endTime",this->spotdata.at(a).end_time);
        spotroot.insert("spot",spot);
        spotList.append(spotroot);
    }
    for(int a=0;a<spotList.count();a++){
        spotArray.append(spotList.at(a));
    }

    spotList.clear();

    QJsonObject rootObject;
    rootObject.insert("song",song);
    rootObject.insert("rhythmSpot",spotArray);

    //test
    QJsonDocument document;
    document.setObject(rootObject);
    byteDatas = document.toJson(QJsonDocument::Indented);


    qDebug()<<byteDatas.data()<<endl;
}

void JsonDataManager::saveDatas(QString fileName, QString filePath){

    QDir dir(filePath+"/datas/");
    if(!dir.exists())
        dir.mkdir(filePath+"/datas/");
//    dir.mkpath(filePath+"/datas/"+fileName);


    QFile file(filePath+"/datas/"+fileName);

    if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
        qDebug()<<"file open failed"<<endl;

    QTextStream out(&file);
    out<<byteDatas;
    file.close();
}
